package com.jsu.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jsu.mapper.ActivityMapper;
import com.jsu.mapper.ActivitySubMapper;
import com.jsu.mapper.AgendaMapper;
import com.jsu.user.mapper.WebUserMapper;
import com.jsu.mapper.AgendaSubMapper;
import com.jsu.user.service.WebUserService;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.example.model.activity.pojo.Activity;
import org.example.model.activity.pojo.ActivitySub;
import org.example.model.activity.pojo.Agenda;
import org.example.model.activity.pojo.AgendaSub;
import org.example.model.common.dtos.ResponseResult;
import org.example.model.common.enums.WebHttpCodeEnum;
import org.example.model.user.pojo.User;
import org.example.utils.common.WebJwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.example.utils.common.IdsUtils;
import org.springframework.util.DigestUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.server.ServerWebExchange;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import static org.example.model.common.enums.RedisCodeEnum.LOGIN;

@Service
@Slf4j
@Transactional
public class WebUserServiceImpl extends ServiceImpl<WebUserMapper, User> implements WebUserService{
    @Autowired
    private WebUserMapper userMapper;
    @Autowired(required = false)
    private AgendaSubMapper agendaSubMapper;
    @Autowired(required = false)
    private AgendaMapper agendaMapper;
    @Autowired(required = false)
    private ActivityMapper activityMapper;
    @Autowired(required = false)
    private ActivitySubMapper activitySubMapper;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private StringRedisTemplate redisCache;

    /**
     * 修改用户信息
     * @param user
     * @return
     */
    @Override
    public ResponseResult updateUser(User user) {

        int count = userMapper.updateById(user);
        if(count>0)
            return new ResponseResult(200,"成功修改");
        return ResponseResult.errorResult(WebHttpCodeEnum.FAIL);
    }

    /**
     * 获取当前用户的个人信息
     * @return user对象
     */
    @Override
    public ResponseResult findUser(String token) {
        //根据手机号查询用户
        long phone = Objects.requireNonNull(WebJwtUtil.getClaimsBody(token)).get("id", Long.class);
        User user = getOne(Wrappers.<User>lambdaQuery().eq(User::getTel,phone));
        if(user==null)
            return ResponseResult.errorResult(WebHttpCodeEnum.DATA_NOT_EXIST,"用户信息不存在");
        return ResponseResult.okResult(user);
    }

//    /**
//     * 获取用户订阅的议程
//     * @return Agenda集合
//     */
//    @Override
//    public ResponseResult getUserAgenda() {
//        //获取用户信息
//        User user = getUser();
//        if(user==null)
//            return ResponseResult.errorResult(WebHttpCodeEnum.DATA_NOT_EXIST,"用户信息不存在");
//        int id = user.getPkId();
//
//        //根据id获取用户的订阅议程ID集合
//        QueryWrapper<AgendaSub> agendaSubQueryWrapper = new QueryWrapper<>();
//        agendaSubQueryWrapper.select("agenda_id")
//                .eq("user_id", id);
//        List<AgendaSub> agendaSubs1 = agendaSubMapper.selectList(agendaSubQueryWrapper);
//        if(agendaSubs1.isEmpty())
//            return ResponseResult.errorResult(WebHttpCodeEnum.DATA_NOT_EXIST,"用户还没有订阅的议程");
//        List<Integer> agendaSubs = agendaSubs1.stream()
//                                     .map(AgendaSub::getAgendaId)
//                                     .collect(Collectors.toList());
//        log.info("获取用户订阅的议程ID集合");
//
//        if (agendaSubs.size()==0||agendaSubs.isEmpty()) {
//            return ResponseResult.errorResult(WebHttpCodeEnum.DATA_NOT_EXIST,"还没有订阅的议程");
//        }
//        //根据议程ID的集合获取议程集合
//        QueryWrapper<Agenda> agendaQueryWrapper = new QueryWrapper<>();
//        agendaQueryWrapper.in("agenda_id", agendaSubs);
//        List<Agenda> agenda = agendaMapper.selectList(agendaQueryWrapper);
//        log.info("获取用户订阅的议程集合");
//
//        if (agenda.size()==0||agenda.isEmpty()) {
//            return ResponseResult.errorResult(WebHttpCodeEnum.FAIL,"出错了");
//        }
//        return ResponseResult.okResult(agenda);
//    }
//
//    /**
//     * 获取用户订阅的精彩活动
//     * @return Activity集合
//     */
//    @Override
//    public ResponseResult getUserActivity() {
//
//        //获得用户的ID
//        User user = getUser();
//        int id = user.getPkId();
//        log.info("当前用户的ID为:"+id);
//        //根据id获取用户的订阅活动ID集合
//        QueryWrapper<ActivitySub> activitySubQueryWrapper = new QueryWrapper<>();
//        activitySubQueryWrapper.select("activity_id")
//                .eq("user_id", id);
//        List<ActivitySub> a =activitySubMapper.selectList(activitySubQueryWrapper);
//        if(a.isEmpty())
//            return ResponseResult.errorResult(WebHttpCodeEnum.DATA_NOT_EXIST,"用户还没有订阅的活动");
//        List<Integer> activitySubs = a.stream()
//                .map(ActivitySub::getActivityId)
//                .collect(Collectors.toList());
//        log.info("获取用户订阅的活动ID集合");
//
//        if (activitySubs.size()==0||activitySubs.isEmpty()) {
//            return ResponseResult.errorResult(WebHttpCodeEnum.DATA_NOT_EXIST,"还没有订阅的议程");
//        }
//
//        //根据议程ID的集合获取活动集合
//        QueryWrapper<Activity> activityQueryWrapper = new QueryWrapper<>();
//        activityQueryWrapper.in("activity_id", activitySubs);
//        List<Activity> activities = activityMapper.selectList(activityQueryWrapper);
//        log.info("获取用户订阅的活动集合");
//
//        if (activities.size()==0||activities.isEmpty()) {
//            return ResponseResult.errorResult(WebHttpCodeEnum.FAIL,"出错了");
//        }
//        return ResponseResult.okResult(activities);
//    }
//

    /**
     * 用户登出
     * @return
     */
    @Override
    public ResponseResult loginOut() {
        //获取当前用户的phone
        String phone =  request.getHeader("phone");
        log.info("当前用户的手机号码为:"+phone);
        //删除redis的用户信息
        if(!Objects.isNull(redisCache.opsForValue().get(LOGIN.getMsg()+phone)))
            redisCache.opsForValue().getOperations().delete(LOGIN.getMsg()+phone);
        return ResponseResult.okResult(phone);
    }

    /**
     * 获取所有用户信息
     * @return
     */
    public ResponseResult findAllUser() {

        List<User> users = getBaseMapper().selectList(null);
        if(users.isEmpty()){
            return ResponseResult.errorResult(WebHttpCodeEnum.DATA_NOT_EXIST,"用户信息不存在");
        }
        return ResponseResult.okResult(users);
    }

    /**
     * 添加用户信息
     * @param user
     * @return
     */
    @Override
    public ResponseResult addUser(User user) {
        //生成id和用户盐值
        int id = IdsUtils.creatCodeTen();
        String salt = "abc";
        try {
            salt = IdsUtils.encryptNumber(2L);
        } catch (Exception e) {
            log.info("生成盐值");
            throw new RuntimeException(e);
        }
        //封装user对象
        user.setPkId(id);
        user.setSalt(salt);
        user.setUsername("用户"+id);
        user.setPassword(DigestUtils.md5DigestAsHex("12345678".getBytes()));
        log.info("添加用户信息:"+user.toString());
        //存入数据库
        int count = getBaseMapper().insert(user);
        if(count>0)
            return ResponseResult.okResult(user);
        return ResponseResult.errorResult(WebHttpCodeEnum.FAIL);
    }

    /**
     * 删除用户信息
     * @param userId
     * @return
     */
    @Override
    public ResponseResult deleteUser(int userId) {
        int count = getBaseMapper().deleteById(userId);
        if(count>0)
            return ResponseResult.okResult(userId);
        return ResponseResult.errorResult(WebHttpCodeEnum.FAIL);
    }

    /**
     * 搜索用户
     * @param keyword
     * @return
     */
    @Override
    public ResponseResult searchUser(String keyword) {
        List<User> users = getBaseMapper().searchUsersByKeyword(keyword);
        if(users.isEmpty()){
            return ResponseResult.errorResult(WebHttpCodeEnum.DATA_NOT_EXIST,"用户信息不存在");
        }
        return ResponseResult.okResult(users);
    }

    /**
     * 批量删除用户信息
     * @param userIds
     * @return
     */
    @Override
    public ResponseResult deleteUserBatch(int[] userIds) {
        List<Integer> idList = Arrays.stream(userIds).boxed().collect(Collectors.toList());
        log.info("批量删除用户信息:"+idList.get(0));
        int count = getBaseMapper().deleteBatchIds(idList);
        if(count>0)
            return ResponseResult.okResult(200,"成功删除"+count+"条数据");
        return ResponseResult.errorResult(WebHttpCodeEnum.FAIL);
    }

    /**
     * 根据用户id获取用户信息
     *
     * @param userId
     * @return
     */
    @Override
    public ResponseResult findUserById(int userId) {
        User user = getOne(Wrappers.<User>lambdaQuery().eq(User::getPkId,userId));
        if(Objects.isNull(user))
            return ResponseResult.errorResult(WebHttpCodeEnum.DATA_NOT_EXIST,"用户信息不存在");
        return ResponseResult.okResult(user);
    }

    @Override
    public ResponseResult findUserByPhone(int phone) {
        User user = getOne(Wrappers.<User>lambdaQuery().eq(User::getTel,phone));
        if(Objects.isNull(user))
            return ResponseResult.errorResult(WebHttpCodeEnum.DATA_NOT_EXIST,"用户信息不存在");
        return ResponseResult.okResult(user);
    }

}
